﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;

namespace CommonLibrary.Helper
{
    public static class JsonHelper
    {
        /// <summary>
        /// 把实体类保存到json
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="classSave">待保存数据类</param>
        /// <param name="fileName">文件名</param>
        /// <returns>返回空字符就是成功，否则则有错误</returns>
        public static string SaveToJson<T>(ref T classSave, string fileName)
        {
            string retString = "";
            //json转换
            string json = JsonConvert.SerializeObject(classSave, Formatting.Indented);
            T? obj = JsonConvert.DeserializeObject<T>(json);
            if (obj != null)
            {
                //retString = isFormat ? SaveSeries(fileName, json) : SaveNoFormat(fileName, json);
                //retString = SaveSeries(fileName, json);
                retString = SaveNoFormat(fileName, json);
            }

            return retString;
        }

        /// <summary>
        /// 把列表保存到json
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="listSave">待保存列表</param>
        /// <param name="fileName">文件名</param>
        /// <param name="isFormat">是否要格式化保存</param>
        /// <returns>返回空字符就是成功，否则则有错误</returns>
        public static string SaveListToJson<T>(ref List<T> listSave, string fileName, bool isFormat = false)
        {
            string retString = "";
            //json转换
            string json = JsonConvert.SerializeObject(listSave, Formatting.Indented);
            IList<T>? obj = JsonConvert.DeserializeObject<List<T>>(json);
            if (obj != null)
            {
                retString = isFormat ? SaveSeries(fileName, json) : SaveNoFormat(fileName, json);
            }

            return retString;
        }

        /// <summary>
        /// 读取没有格式的json到列表
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="fileName">读取的json文件名</param>
        /// <param name="outClass">输出列表</param>
        /// <param name="converter"></param>
        /// <returns>返回空字符就是成功，否则则有错误</returns>
        public static string ReadJson<T>(string fileName, out T? outClass, JsonConverter? converter = null)
        {
            string jsonString = ReadSeriesNoFormat(fileName);
            if (!string.IsNullOrEmpty(jsonString))
            {
                try
                {
                    outClass = converter == null ? JsonConvert.DeserializeObject<T>(jsonString) :
                        JsonConvert.DeserializeObject<T>(jsonString, converter);
                }
                catch
                {
                    outClass = default;
                    return "读取失败";
                }

                return "";
            }
            outClass = default;
            return "读取失败";
        }

        /// <summary>
        /// 读取没有格式的json到列表
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="fileName">读取的json文件名</param>
        /// <param name="outList">输出列表</param>
        /// <param name="converter"></param>
        /// <returns>返回空字符就是成功，否则则有错误</returns>
        public static string ReadJsonToList<T>(string fileName, out IList<T>? outList, JsonConverter? converter = null)
        {
            string jsonString = ReadSeriesNoFormat(fileName);
            if (!string.IsNullOrEmpty(jsonString))
            {
                outList = converter == null ? JsonConvert.DeserializeObject<List<T>>(jsonString) :
                                              JsonConvert.DeserializeObject<List<T>>(jsonString, converter);

                return "";
            }

            outList = null;
            return "读取失败";
        }

        /// <summary>
        /// 不格式化保存Json文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private static string SaveNoFormat(string fileName, string content)
        {
            using var writer = new StreamWriter(fileName);
            try
            {
                writer.Write(content);
                writer.Close();
                return "";
            }
            catch (Exception ex)
            {
                return "保存失败" + ex.Message.ToString();
            }
        }

        /// <summary>
        /// 格式化保存json文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        private static string SaveSeries(string fileName, string json)
        {
            using var writer = new StreamWriter(fileName);
            try
            {
                var array = JArray.Parse(json);
                writer.Write(array.ToString());
                writer.Close();
                return "";
            }
            catch (Exception ex)
            {
                return "保存失败" + ex.Message.ToString();
            }
        }

        //读取json文件
        public static string ReadSeriesNoFormat(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return string.Empty;
            }
            using var reader = new StreamReader(fileName);
            try
            {
                string buff = reader.ReadToEnd();
                reader.Close();
                return buff;
            }
            catch
            {

            }

            return string.Empty;
        }

    }
}
